package com.cloud.phone.service;

import android.accessibilityservice.AccessibilityService;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.task.BaseTask;
import com.cloud.phone.task.MsgTaskManger;
import com.cloud.phone.task.TaskManager;
import com.cloud.phone.task.bean.BeAttentionChatBean;
import com.cloud.phone.task.bean.MsgTaskBean;
import com.cloud.phone.task.bean.ServerInnerDataBean;
import com.cloud.phone.task.bean.ServerTaskDataBean;
import com.cloud.phone.task.taskCongfig.TaskTypeConfig;
import com.cloud.phone.tools.AccessibilityTool;
import com.cloud.phone.tools.AutoUtil;
import com.cloud.phone.tools.MyUtils;
import com.cloud.phone.view.TsUtils;
import com.cloud.phone.websocket.WebsocketUtil;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;


/**
 * 自动点赞评论养号辅助
 * 适配版本 14.8.0 适配机型 小米9
 */
public class AccessibilityAutoMainService extends AccessibilityService {
    public boolean isServiceRunning;
    public boolean isWorking;
    AccessibilityEvent currentEvent;
    //刷新node节点的时间
    private long refreshNodeTime =1000;
    private long checkLoginStatusTaskDelayTime =1000*60*10;//每间隔10分钟检测一次账号状态
    public long changeStatusTime;
    private Map<Integer, Boolean> handledMap = new HashMap<>();
    private static final String TAG = "AccessibilityMainService";

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        if(event.getKeyCode()==KeyEvent.KEYCODE_VOLUME_DOWN){
            if(System.currentTimeMillis()-changeStatusTime<1000){
                return super.onKeyEvent(event);
            }
            changeStatusTime=System.currentTimeMillis();
           //点击音量下键
            if(!TaskManager.getInstance().tasks.isEmpty()) {
                if(TaskManager.getInstance().tasks.get(0).taskStatus== BaseTask.RUNNING_TASK
                ||TaskManager.getInstance().tasks.get(0).taskStatus== BaseTask.ON_START_TASK) {
                    TaskManager.getInstance().tasks.get(0).onTaskStop();
                }else{
                    if(TaskManager.getInstance().tasks.get(0).taskStatus== BaseTask.STOP) {
                        TaskManager.getInstance().tasks.get(0).onTaskResume();
                    }
                }
            }
        }
        return super.onKeyEvent(event);
    }


    @Override
    public void onAccessibilityEvent(final AccessibilityEvent event) {
        currentEvent = event;
//        AccessibilityTool.getInstance().findNodeInfoAllInPage(null,this,"",false);
        //无障碍自动安装apk
    }

    private boolean iterateNodesAndHandle(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo != null) {
            int childCount = nodeInfo.getChildCount();
            if (TextUtils.equals("android.widget.Button",nodeInfo.getClassName())) {
                String nodeContent = nodeInfo.getText().toString();
                LogUtils.d(TAG, "content is " + nodeContent);
                if ("安装".equals(nodeContent)
                        || "打开".equals(nodeContent)
                        || "确定".equals(nodeContent)) {
                    nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    return true;
                }
            } else if (TextUtils.equals("android.widget.ScrollView",nodeInfo.getClassName())) {
                nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
            }
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo childNodeInfo = nodeInfo.getChild(i);
                if (iterateNodesAndHandle(childNodeInfo)) {
                    return true;
                }
            }
        }
        return false;
    }



    public String getCurrentAcName() {
        if(currentEvent==null){
            return null;
        }
        String name = currentEvent.getClassName().toString();
        if (name.contains("com.")) {
            if (name.contains(currentEvent.getPackageName())) {
                name = name.replace(currentEvent.getPackageName().toString(), "");
                name = name.replace("..", "");
                if (name.charAt(0) == '.')
                    name = name.substring(1);
            }
        }
        return name;
    }


    /**
     * 开启一个线程更新当前最新的节点信息
     */
    public void startThreadToUpdateCurrentRootNode(){
        TaskManager.getInstance().setAccessibilityService(this);
        AutoUtil.getInstance().setService(this);
        new Thread(){
            @Override
            public void run() {
                while (isServiceRunning){
                    try {
                        TaskManager.getInstance().onTaskDoing();
                        Thread.sleep(refreshNodeTime);
                        checkIsNeedDoLoopTask();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }.start();
    }


    /**
     * 检测是否需要执行循环定时任务
     */
    private void checkIsNeedDoLoopTask() {
        BaseTask task = TaskManager.getInstance().getCurrentTask();
        if(task!=null&&task.currentTaskType==TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO){
            return;
        }
        boolean isWorking = false;
        if(Constants.TASK_IS_RUNNING){
            sendCurrentStatusToServer(true);
            return;
        }
        if(task==null){
            if(needLoopUpdatePhoneInfo){
                needLoopUpdatePhoneInfo=false;
                if(!isOpenBeAttentionReplayTask()){
                    sendCurrentStatusToServer(false);
                    return;
                }
                LogUtils.e("当前任务为空了，并且可以执行定时更新任务了");
                createUpdatePhoneInfoTask();
                isWorking=true;
            }
        }else{
            if (task.taskStatus > BaseTask.RUNNING_TASK) {
                if (needLoopUpdatePhoneInfo) {
                    needLoopUpdatePhoneInfo = false;
                    if(!isOpenBeAttentionReplayTask()){
                        sendCurrentStatusToServer(false);
                        return;
                    }
                    LogUtils.e("当前任务运行状态变为"+task.taskStatus+"了，并且可以执行定时更新任务了");
                    createUpdatePhoneInfoTask();
                    isWorking=true;
                }
            } else {
                isWorking = true;
            }
        }
        sendCurrentStatusToServer(isWorking);
    }


    long lastSendTime=0;
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss");
    public synchronized void sendCurrentStatusToServer(boolean isWorking){
        if(!WebsocketUtil.getWebsocketUtil().isActivityInTask()){
            return;
        }
        if(System.currentTimeMillis()-lastSendTime>5000) {
            this.isWorking=isWorking;
            MsgTaskBean msgTaskBean = new MsgTaskBean();
            msgTaskBean.setCode(1005);
            String phoneId=WebsocketUtil.getWebsocketUtil().getPhoneId();
            msgTaskBean.setToken(SPUtils.getInstance().getString("token"));
            msgTaskBean.setTaskType(TaskTypeConfig.UPDATE_CURRENT_TASK_STATUS);
            JsonObject jsonObject=new JsonObject();
            jsonObject.addProperty("isWorking",isWorking);
            jsonObject.addProperty("phoneId",phoneId);
            ServerInnerDataBean serverInnerDataBean=new ServerInnerDataBean();
            serverInnerDataBean.setJson(GsonUtils.toJson(jsonObject));
            msgTaskBean.setData(serverInnerDataBean);
            WebsocketUtil.getWebsocketUtil().sendMsg(GsonUtils.toJson(msgTaskBean));
            lastSendTime=System.currentTimeMillis();
            MsgTaskManger.showLog("isWorking="+isWorking);
//            MsgTaskManger.showLog(simpleDateFormat.format(new Date())+"\n-发送isWorking:"+isWorking);
        }
    }


    public boolean needLoopUpdatePhoneInfo;
    //开启一个状态更新的线程进行循环定时任务
    public void startStatusUpdateThreadToSendServer(){
        new Thread(){
            @Override
            public void run() {
                while (isServiceRunning){
                    try {
                        BaseTask task = TaskManager.getInstance().getCurrentTask();
                        if(task!=null&&task.currentTaskType==TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO
                                &&task.taskStatus!=BaseTask.FINISH
                        ){
                            //说明正在执行更新状态的任务并且还未完成
                            Thread.sleep(5000);
                            continue;
                        }
                        Thread.sleep(checkLoginStatusTaskDelayTime);
                        if(task==null){
                            if(!isOpenBeAttentionReplayTask()){
                                continue;
                            }
                            createUpdatePhoneInfoTask();
                        }else{
                            if(task.taskStatus!=BaseTask.RUNNING_TASK&&task.taskStatus!=BaseTask.WAIT
                                    &&task.taskStatus!=BaseTask.ON_START_TASK){
                                if(!isOpenBeAttentionReplayTask()){
                                    continue;
                                }
                                createUpdatePhoneInfoTask();
                            }else{
                                if(task.currentTaskType!=TaskTypeConfig.TIKTOK_GET_USER_INFO
                                        &&task.currentTaskType!=TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO
                                        &&task.currentTaskType!=TaskTypeConfig.TIKTOK_TASK_AUTO_REPLAY_BE_ATTENTION){
                                    needLoopUpdatePhoneInfo=true;
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        TsUtils.showTips("更新状态信息任务中断了");
                    }
                }
            }
        }.start();
    }

    /**
     * 是否开启被关注后自动回复任务
     * @return
     */
    public boolean isOpenBeAttentionReplayTask(){
        String beAttentionChatBeanStr = SPUtils.getInstance().getString(BeAttentionChatBean.class.getSimpleName());
        if(MyUtils.isEmpty(beAttentionChatBeanStr)){
            return false;
        }
        BeAttentionChatBean serverTaskInnerBean= GsonUtils.fromJson(beAttentionChatBeanStr,BeAttentionChatBean.class);
        if(MyUtils.isEmpty(serverTaskInnerBean.getBeAttentionChatListBeans())){
            return false;
        }
        return true;
    }

    private void createUpdatePhoneInfoTask() {
        BaseTask currentTask = TaskManager.getInstance().getCurrentTask();
        if(currentTask!=null
                &&currentTask.currentTaskType==TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO
                &&currentTask.taskStatus<BaseTask.FINISH){
            //更新任务已存在，无需创建
            LogUtils.i("更新信息任务已存在并正在运行，无需创建新任务");
            return;
        }
        ServerTaskDataBean serverTaskDataBean=new ServerTaskDataBean();
        serverTaskDataBean.setTaskType(TaskTypeConfig.TIKTOK_UPDATE_CURRENT_APP_LOGIN_INFO);
        TaskManager.getInstance().createTikTokTask(serverTaskDataBean);
        LogUtils.i("检测是否需要更新状态信息:"+"创建了一个更新信息的任务执行");
        MsgTaskManger.showLog("创建定时更新任务");
        needLoopUpdatePhoneInfo=false;
        String pkgName = AccessibilityTool.getInstance().getCurrentPagePackageName(this);
        if(!Constants.tiktokPackageName.equals(pkgName)){
            TaskManager.getInstance().onOpenTaskApp(currentTask,Constants.tiktokPackageName);
        }
    }


    @Override
    public void onInterrupt() {
        isServiceRunning=false;
    }



    private void showTs(final String msg) {
        LogUtils.i("当前操作："+msg);
        TsUtils.showTips(msg);
    }




    private void showDialog(final String msg) {
        Handler handlerThree=new Handler(Looper.getMainLooper());
        handlerThree.post(new Runnable(){
            public void run(){
                AlertDialog.Builder msgDialog=new AlertDialog.Builder(getApplicationContext());
                msgDialog.setTitle("系统提示");
                msgDialog.setMessage(msg);
                msgDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                msgDialog.show();
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        isServiceRunning=false;
    }


    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        LogUtils.i("无障碍服务开启成功，刷新最新节点信息");
        isServiceRunning=true;
        MsgTaskManger.showLog("开启无障碍服务成功：activity是否存活->"+WebsocketUtil.getWebsocketUtil().isActivityInTask());
        startThreadToUpdateCurrentRootNode();
//        startStatusUpdateThreadToSendServer();
    }
}